package com.azzaou.controller;

import java.io.IOException;
import java.io.Serializable;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.azzaou.enums.StatusException;
import com.azzaou.model.User;
import com.azzaou.service.IUserService;
import com.azzaou.util.ErrorHandler;
import com.azzaou.util.GlobalUtil;
import com.azzaou.view.LoginView;

/**
 * class LoginController
 * 
 */
public class LoginController implements Serializable
{
  /**
   * serialVersionUID
   */
  private static final long serialVersionUID = 1L;

  /**
   * Logger for this class
   */
  private static final Logger LOGGER = 
    Logger.getLogger(LoginController.class);
  

  /**
   * ec
   */
  public ExternalContext context;
  
  /**
   * request
   */
  HttpServletRequest request;
  
  /**
   * httpSession
   */
  HttpSession httpSession;

  /**
   * userManagement Service
   */
  IUserService userService;

  /**
   * userManagement
   */
  LoginView loginView;
  
  /**
   * Error Handler
   */
  private ErrorHandler errorHandler;

  
  /**
   * Constructor
   */
  public LoginController()
  {
    super();
  }

 /**
   * login Action
   * 
   * @return String
   */
  public String loginAction()
  {
    LOGGER.info("Login Action : Begin");

    try
    {
      if ((loginView.getLogin() == null || "".equalsIgnoreCase(loginView
          .getLogin()))
          || (loginView.getPassword() == null || "".equalsIgnoreCase(loginView
              .getLogin())))
      {
        return "";
      }
      if (userService != null) 
      {
          User user = userService.login(loginView.getLogin(), GlobalUtil.md5(loginView.getPassword()));
          context = FacesContext.getCurrentInstance().getExternalContext();
          request = (HttpServletRequest)context.getRequest();
          httpSession = request.getSession();

          if (user != null)
          {
            LOGGER.info("User exist in DOD");
             loginView.setLogin(user.getLogin());

              loginView.setAlertStyle(null);
              loginView.setAlertValue(null);
              loginView.setAlertMsg(null);

              // Set session user
              httpSession.setAttribute("authenticated", "success");
               context.redirect(request.getContextPath()
               + "/pages/chantiers.jsf");
          }
          else
          {
        	 httpSession.setAttribute("authenticated", "success");
             context.redirect(request.getContextPath() + "/login.jsf");
          }
        }
    }
    catch (Exception e)
    {
        errorHandler.setException(e);
        try
        {
          context
          .redirect(request.getContextPath() + "/login.jsf");
        }
        catch (IOException e1)
        {
          LOGGER.error("An error occurred during authentication : " + e.fillInStackTrace());
        }
        LOGGER.error("An exception occurred during authentication : " + e.fillInStackTrace());
      }

    LOGGER.info("login Action - end");
    return "";
  }

  /**
   * clear Form
   */

  public void clearForm()
  {
    LOGGER.info("clear login form ");
    loginView.setLogin("");
    loginView.setPassword("");
  }

  /***
   * logout
   * 
   * @return String
   */
  public String logout()
  {
    LOGGER.info("Disconnecting from application");
    try
    {
      ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
      HttpSession session = ((HttpSession)ectx.getSession(false));
      if (session != null)
      {
         session.invalidate();
         errorHandler.setAuthenticationTitle("Autentication");
         errorHandler.setAuthenticationError("You are disconnected from the application. ");
         ectx.redirect(request.getContextPath() + "/login.jsf");
      }
    }
    catch (Exception e)
    {
      LOGGER.error("An error occurred when closing the session : " + e);
    }

    return "logout";
  }

  
  /**
   * getuserService
   * 
   * @return the userService
   */
  public IUserService getuserService()
  {
    return userService;
  }

  /**
   * setuserService
   * 
   * @param puserService
   *          the userService to set
   */
  public void setuserService(
      IUserService pUserService)
  {
    this.userService = pUserService;
  }

  /**
   * getLoginView
   * 
   * @return the loginView
   */
  public LoginView getLoginView()
  {
    return loginView;
  }

  /**
   * setLoginView
   * 
   * @param pLoginView
   *          the loginView to set
   */
  public void setLoginView(LoginView pLoginView)
  {
    this.loginView = pLoginView;
  }

  /**
   * @return errorHandler
   */
  public ErrorHandler getErrorHandler()
  {
    return errorHandler;
  }

  /**
   * @param errorHandler errorHandler to define
   */
  public void setErrorHandler(ErrorHandler errorHandler)
  {
    this.errorHandler = errorHandler;
  }

}
